<template>
  <div>
    <el-form ref="registerForm" :model="registerForm" class="register-form" :rules="registerRules">
      <el-form-item prop="username">
        <el-input v-model="registerForm.username" type="text" auto-complete="off" placeholder="账号">
          <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="registerForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleRegister">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          auto-complete="off"
          placeholder="确认密码"
          @keyup.enter.native="handleRegister">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="registerForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleRegister">
          <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
        </el-input>
        <div class="register-code">
          <img :src="codeUrl" @click="$emit('getCode')" class="register-code-img" />
        </div>
      </el-form-item>
      <slot name="phoneCode"></slot>
      <slot name="emailCode"></slot>
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width: 100%"
          @click.native.prevent="handleRegister">
          <span v-if="!loading">注 册</span>
          <span v-else>注 册 中...</span>
        </el-button>
        <div style="float: right">
          <router-link class="link-type" :to="'/login'">使用已有账户登录</router-link>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { sendPhoneCode, sendEmailCode } from "@/api/system/verifyCode"
import { isExist, checkCode } from "@/api/system/user"

export default {
  name: "RegisterCommon",
  props: {
    registerForm: Object,
    btnControl: Object,
    captchaEnabled: Boolean,
    codeUrl: String,
  },
  data() {
    const equalToPassword = (rule, value, callback) => {
      if (this.registerForm.password !== value) {
        callback(new Error("两次输入的密码不一致"))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      registerRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" },
          {
            min: 2,
            max: 20,
            message: "用户账号长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        confirmPassword: [
          { required: true, trigger: "blur", message: "请再次输入您的密码" },
          { required: true, validator: equalToPassword, trigger: "blur" },
        ],
        code: [{ required: true, trigger: "blur", message: "请输入验证码" }],
        authCode: { required: true, trigger: "blur", message: "请输入验证码" },
        phoneNumber: [
          { required: true, trigger: "blur", message: "请输入手机号" },
          {
            pattern: /^(?:0|86|\+86)?1[3456789]\d{9}$/,
            message: "请输入正确的手机号",
          },
        ],
        email: [
          { required: true, trigger: "blur", message: "请输入邮箱" },
          {
            pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/,
            message: "请输入正确的邮箱",
          },
        ],
      },
    }
  },
  methods: {
    handleRegister() {
      this.$refs.registerForm.validate((valid) => {
        if (valid) {
          this.$emit("handleRegister")
        }
      })
    },
    doBtnControl(sendType) {
      let btnName = "emailValidateCodeBtn"
      let btnTextName = "emailValidateCodeBtnText"
      if (sendType === "phone") {
        btnName = "phoneValidateCodeBtn"
        btnTextName = "phoneValidateCodeBtnText"
      }
      this.btnControl[btnName] = true
      this.$modal.msgSuccess("验证码发送成功，5分钟内有效")
      this.btnControl[btnName] = true
      let count = 60
      let timer = setInterval(() => {
        count--
        this.btnControl[btnTextName] = count + "s后重新发送"
        if (count == 0) {
          this.btnControl[btnTextName] = "发送验证码"
          this.btnControl[btnName] = false
          clearInterval(timer)
        }
      }, 1000)
    },
    sendAuthCode(sendType) {
      let field = sendType == "phone" ? "phoneNumber" : sendType
      this.$refs["registerForm"].validateField(field, (err) => {
        if (!err) {
          isExist({
            type: sendType,
            account: this.registerForm[field],
          }).then((res) => {
            if (!res.data) {
              if (sendType === "phone") {
                sendPhoneCode(this.registerForm.phoneNumber).then(() => {
                  this.doBtnControl(sendType)
                })
              } else if (sendType === "email") {
                sendEmailCode(this.registerForm.email).then(() => {
                  this.doBtnControl(sendType)
                })
              }
            } else {
              this.$modal.msgError(sendType=="phone"?"手机号已注册":"邮箱已注册")
            }
          })
        }
      })
    },
  },
}
</script>

<style></style>
